<template>
  <div>
    <el-dialog
      title="新增设备"
      :visible.sync="dialogVisible"
      width="427px"
      style="text-align:center"
    >
      <el-form
        label-width="90px"
        status-icon
        ref="form"
        :model="form"
        :rules="rules"
        size="mini"
        style="text-align:left"
      >
        <!-- 单位部门 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="单位部门:" >
              <div class="treeselect">
                <!-- v-model="form.deptId" -->
                <treeselect
                  v-model="form.deptId"
                  :options="deptOptions"
                  :searchable="false"
                  :show-count="true"
                  :clearable="false"
                  placeholder="请选择所属部门"
                  @select="treeselect"
                  style="width:297px"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 模式 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="添加模式:">
              <el-select v-model="fPattern" style="width:297px">
                <el-option
                  v-for="item in fPatternOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  style="text-indent:1em"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 单卡模式 -->
        <el-row v-if="fPattern === 1">
          <el-col :span="24">
            <el-form-item label="设备编号:" prop="fNumber" style="width:65%">
              <el-input
                placeholder="请输入设备编号"
                v-model="form.fNumber"
                maxlength="12"
                style="width:297px"
                @blur="getCardLen"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 批量模式 -->
        <el-row v-else>
          <el-col :span="12">
            <el-form-item label="设备编号:" prop="fNumber">
              <!--  @change="getVal" -->
              <el-input
                placeholder="终端号"
                v-model="form.fNumber"
                maxlength="9"
                @focus="getFocus"
                @blur="getCardLen"
              />
            </el-form-item>
          </el-col>
          <!-- 前缀 -->
          <el-col :span="6">
            <el-form-item label-width="5px" prop="prefix">
              <el-input
                placeholder="前缀"
                v-model.number="form.prefix"
                :maxlength="prefixLength"
                @focus="getFocus"
              />
            </el-form-item>
          </el-col>
          <!-- 后缀 -->
          <el-col :span="6">
            <el-form-item label-width="5px" prop="suffix">
              <el-input
                placeholder="后缀"
                v-model.number="form.suffix"
                :maxlength="suffixLength"
                @focus="getFocus"
                @blur="getMoreCard"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 宽度 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备宽度:" style="width:65%">
              <el-input
                placeholder="请输入设备宽度"
                v-model="form.fWidth"
                disabled
                style="width:297px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 高度 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备高度:" style="width:65%">
              <el-input
                placeholder="请输入设备高度"
                v-model="form.fHeight"
                disabled
                style="width:297px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 类型 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备类型:" style="width:65%">
              <el-select
                v-model="form.fType"
                placeholder="请选择设备类型"
                style="width:297px"
                disabled
              >
                <el-option
                  v-for="item in cardTypeOptions"
                  :key="item.fType"
                  :label="item.fDescription"
                  :value="item.fType"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 描述 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备描述:">
              <el-input v-model="form.fDescription" style="width:297px"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- button -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 存在批量卡号Dialog -->
    <el-dialog
      width="30%"
      center
      :visible.sync="dialogTableVisible"
      close-on-press-escape
    >
      <div slot="title" class="dialog-title">
        <p class="el-icon-warning"><span>警告:有存在的设备编号</span></p>
      </div>
      <el-table :data="cardData" border height="400">
        <el-table-column type="index" width="50" label="序列" align="center">
        </el-table-column>
        <el-table-column align="center" label="卡号">
          <template slot-scope="scope">{{ scope.row }}</template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import {
  addSingle, // 添加单个模式
  addMoreCard, // 添加批量模式
  singleCard, // 查询单个模式
  moreCard, // // 查询批量模式
  cardType, // 设备类型
  cardGroupConfig // 卡组配置信息
} from '@/api/equipment/list' // import api
import { mapState } from 'vuex'
import { Loading } from 'element-ui'
import { treeselects } from '@/api/system/map'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'addDialog',
  props: {
    queryParams: {
      type: Object
    }
  },
  components: {
    Treeselect
  },
  data () {
    return {
      dialogVisible: false, // 是否显示编辑弹出层
      fPattern: 1, // 设备模式
      prefixLength: 5, // 前缀长度
      suffixLength: 5, // 后缀长度
      dialogTableVisible: false, // 存在重复卡号Dialog
      cardData: undefined, // 存在重复卡号表格
      deptOptions: [],
      // 新增或编辑模型
      form: {
        deptId: undefined, // 部门id
        fType: undefined, // 设备类型
        fDescription: undefined, // 描述-名称
        fHeight: undefined, // 屏幕高度
        fWidth: undefined, // 屏幕宽度
        fNumber: undefined, // 设备编号-终端号前缀
        prefix: undefined, // 开始号
        suffix: undefined // 结束号
      },
      cardTypeOptions: [], // 卡号类型信息
      // 添加模式
      fPatternOptions: [
        {
          value: 1,
          label: '单个'
        },
        {
          value: 2,
          label: '批量'
        }
      ],
      // 表单校验
      rules: {
        // 添加模式
        fNumber: [
          {
            required: true,
            validator: async (rule, value, callback) => {
              let count = 0
              // 正则效验要求数字和字母各自最少出现一次
              let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{1,}$/
              if (!value) {
                callback(new Error('设备编号不能为空'))
              } else {
                count++
              }
              // 单个模式
              if (this.fPattern === 1) {
                if (`${value}`.length != 12) {
                  callback(new Error('设备编号长度在 12 位'))
                } else {
                  count++
                }
                if (count === 2) {
                  if (!reg.test(value)) {
                    callback('设备编号不合法')
                  } else {
                    const res = await singleCard(value) // 发送请求
                    let result = res.data.includes(value) // 判断值是否存在
                    if (result) {
                      callback(new Error('该设备编号已存在'))
                    }
                  }
                }
              } else {
                // 批量模式
                let sLen = `${this.form.suffix || ''}${value || ''}`.length
                if (value.length < 7 || value.length > 9) {
                  callback(new Error('长度在 7 到 9 位'))
                } else if (sLen > 12) {
                  this.$message.error('设备编号长度在12位')
                  this.form.suffix = undefined
                  this.form.prefix = undefined
                } else if (!reg.test(value)) {
                  callback(new Error('设备编号不合法'))
                }
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        // 前缀
        prefix: [
          { required: true, message: '前缀不能为空', trigger: 'blur' },
          { type: 'number', message: '前缀必须为数字' },
          {
            required: true,
            validator: (rule, value, callback) => {
              let sLen = this.form.suffix
              if (value < sLen) {
                this.$refs.form.clearValidate('suffix')
              }
              callback()
            },
            trigger: 'change'
          }
        ],
        // 后缀
        suffix: [
          {
            required: true,
            message: '后缀不能为空',
            trigger: ['change', 'blur']
          },
          {
            required: true,
            validator: (rule, value, callback) => {
              let pLen = this.form.prefix
              if (value <= pLen) {
                callback(new Error('前缀比后缀大'))
              }
              callback()
            },
            trigger: ['blur', 'change']
          },
          { type: 'number', message: '后缀必须为数字' }
        ]
      }
    }
  },
  methods: {
    // getVal (value) {
    //   let fLen = this.form.fNumber.toString().length
    //   let pLen = value.toString().length
    //   if (pLen + fLen != fLen * 2) {
    //     return this.getVal(`0${value}`)
    //   }
    //   return `${this.form.fNumber}${value}`
    // },
    // 新增或编辑提交
    submitForm () {
      let loadingInstance
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // 单个模式
        if (this.fPattern !== 2) {
          // Loading 加载
          loadingInstance = Loading.service({
            text: '拼命加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.8)'
          })
          // 请求接口
          const res = await addSingle({
            ...this.form
          })
          if (res.code === 200) {
            // 提示
            this.$message.success(res.msg)
            // 关闭dialog对话框
            this.dialogVisible = false
            // 清空设备编号
            this.$parent.queryParams.fNumber = undefined
            // 清空设备名称
            this.$parent.queryParams.fDescription = undefined
            // 刷新表格数据
            this.$emit('dialogEvent')
            // this.$emit('getTree')
            // 关闭Loading
            loadingInstance.close()
          } else {
            // 提示
            this.$message.error('错误,请联系管理员')
            // 关闭Loading
            loadingInstance.close()
          }
        } else {
          // Loading 加载
          loadingInstance = Loading.service({
            text: '拼命加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.8)'
          })
          // 批量模式模式
          const res = await addMoreCard(
            { ...this.form },
            this.form.prefix,
            this.form.suffix
          )
          if (res.code === 200) {
            // 提示
            this.$message.success(res.msg)
            // 关闭dialog对话框
            this.dialogVisible = false
            this.fPattern = 1
            // 重新渲染表格数据
            this.$emit('dialogEvent')
            this.$emit('getTree')
            // 关闭Loading
            loadingInstance.close()
          } else {
            // 提示
            this.$message.error('错误,请联系管理员')
            // 关闭Loading
            loadingInstance.close()
          }
        }
      })
    },
    // 取消
    cancel () {
      this.dialogVisible = false
      this.fPattern = 1
    },
    // 获取设备编号长度和转换大写
    getCardLen () {
      let fLen = `${this.form.fNumber || ''}`.length
      // 失去焦点非空转换大写字母
      if (fLen) {
        this.form.fNumber = this.form.fNumber.toUpperCase()
      }
    },
    // 查询批量卡号是否存在
    async getMoreCard () {
      let count = 0
      this.$refs.form.validateField(
        ['fNumber', 'prefix', 'suffix'],
        errorMessage => {
          if (!errorMessage) {
            count++
          }
          return count
        }
      )
      if (count === 3) {
        let res = await moreCard(
          this.form.fNumber,
          this.form.prefix,
          this.form.suffix
        )
        if (res.code === 200) {
          if (res.data.length) {
            this.dialogTableVisible = true
            this.cardData = res.data // 把重复的值赋值给表格
            this.form.prefix = undefined
            this.form.suffix = undefined
          }
        }
      }
    },
    // 卡号类型信息
    async getCardType () {
      const res = await cardType()
      if (res.code === 200) {
        this.cardTypeOptions = res.data
      }
    },
    // 卡组配置信息
    async getCardGroupConfig () {
      // setTimeout(async () => {
      const res = await cardGroupConfig(this.queryParams.deptId)
      // console.log(res)
      if (res.code === 200) {
        this.form.fWidth = res.data.width
        this.form.fHeight = res.data.height
        this.form.fType = res.data.fType
      }
      // }, 500)
    },
    // 根据设备编号的长度给前缀和后缀长度赋值
    getFocus () {
      let fLen = `${this.form.fNumber || ''}`.length
      // console.log(fLen)
      switch (fLen) {
        case 7:
          this.suffixLength = 5
          this.prefixLength = 5
          break
        case 8:
          this.suffixLength = 4
          this.prefixLength = 4
          break
        case 9:
          this.suffixLength = 3
          this.prefixLength = 3
          break
        default:
          break
      }
    },
    // 获取部门列表
    async maptreeselects () {
      const res = await treeselects()
      if (res.code === 200 && res.data.length > 0) {
        this.deptOptions = res.data
        // this.form.deptId = res.data[0].id
      }
    },
    // treeselect根据id
    async treeselect (node) {
      this.queryParams.deptId = node.id
      const res = await cardGroupConfig(this.queryParams.deptId)
      if (res.code === 200) {
        this.form.fWidth = res.data.width
        this.form.fHeight = res.data.height
        this.form.fType = res.data.fType
      }
    }
  },
  created () {
    this.form.deptId = this.deptId
    // console.log(this.form.deptId)
    this.maptreeselects()
    this.getCardType()
  },
  mounted () {},
  computed: {
    ...mapState({
      deptId: state => state.deptId
    })
  },
  watch: {
    // 关闭对话框清空效验
    dialogVisible (newVal, oldVal) {
      if (!newVal) {
        this.$refs.form.resetFields()
        this.form.fDescription = ''
      }
      this.fPattern = 1
      this.getCardGroupConfig()
    },
    // 切换单个或批量模式清除表单的值
    fPattern () {
      this.$refs.form.resetFields()
      this.form.fDescription = ''
    }
  }
}
</script>
<style lang="scss" scoped>
.dialog-title {
  color: #ffba00;
  font-size: 40px;
  .el-icon-warning {
    margin: 0;
  }
  span {
    color: #fff;
    font-size: 20px;
    position: relative;
    left: 10px;
    top: -5px;
  }
}
.el-form-item--mini.el-form-item {
  margin-bottom: 15px;
}
</style>
